package com.erp.framework.controller.action;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.erp.app.common.ProjectConstants;
import com.erp.common.web.ActionMethodDispatcher;
import com.erp.framework.SimpleConstants;
import com.erp.framework.controller.form.SimpleUserStyleForm;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

/**
 * @author Lam.Luo
 *
 */
public abstract class SimpleUserStyleActionTemplate extends
		SimpleUserStyleAction {
	
	protected abstract String getFunctionId();
    protected abstract String getUserFormSessionName();
    protected abstract Class getUserFormClass();
    
    protected abstract void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors);
    
    ////////////////////
	protected ActionForward handlePageEvent(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        ActionForward actionForward = new ActionForward(mapping.getInput());
        if (this.isHandled(request)) {
            return actionForward;
        }
        try {
            SimpleUserStyleForm form = (SimpleUserStyleForm) formIn;
            actionForward = new ActionMethodDispatcher()
                .setAction(this)
                .setDefaultActionForward(actionForward)
                .processAction(form.getPageEvent(), mapping, form, request, response, errors);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
        this.saveToken(request);
        this.setHandled(request);
        return actionForward;
    }

    protected ActionForward processOtherStatus(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {
        ActionForward actionForward = new ActionForward(mapping.getInput());
        try {
            SimpleUserStyleForm form = (SimpleUserStyleForm) formIn;
            actionForward = new ActionMethodDispatcher()
                .setAction(this)
                .setDefaultActionForward(actionForward)
                .setProcessStatus(true)
                .setStatus(rb_status)
                .processAction(form.getPageEvent(), mapping, form, request, response, errors);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
        this.saveToken(request);
        this.setHandled(request);
        return actionForward;
    }

	protected ActionForward otherExecute(ActionMapping mapping,
			ActionForm formIn, HttpServletRequest request,
			HttpServletResponse response) throws ServletException {
		ActionForward actionForward = null;
        try {
            HttpSession session = request.getSession(false);
            ActionErrors errors = new CustomActionErrors(new ActionErrors());
            SimpleUserStyleForm form = (SimpleUserStyleForm) formIn;
            String action = form.getPageEvent();

            action = CommonUtil.isEmpty(action) ? "" : action.trim();
            actionForward = new ActionForward(mapping.getInput());
            

            String rb_status = CommonUtil.nullToString((String) session.getAttribute(getSessionSimpleUserStatus()));
            session.removeAttribute(getSessionSimpleUserStatus());

            Logger.debug(this, "action = " + action + ", mode = " + form.getPageMode() + ", rb_status=[" + rb_status + "]");
            Logger.debug(this, "isHandled=" + isHandled(request));

            initAction(mapping, formIn, request, response, errors);

            setFormType(mapping, form, request, response, errors);
            
            if (!isHandled(request) && !rb_status.equals("")) {
                setHandled(request);
                actionForward = processStatus(mapping, formIn, request, response, errors, rb_status);
            }

            // for initial status
            if (!isHandled(request) && action.length() == 0) {
                setHandled(request);
                initForm(mapping, formIn, request, response, errors);
            }

//            try{
//               // Sets the TableSchema
//                super.copyTsFromVoToForm(mapping, formIn, request, response, null); 
//                session.setAttribute(getUserFormSessionName(), formIn);
//            } catch(Exception e){
//                Logger.logExceptions(this, e);
//            }
            if (!isHandled(request) && action.equalsIgnoreCase(ACTION_EXIT)) {
                Logger.all(this, "otherExecute(),actionExit,action=" + action);
                setHandled(request);
                actionForward = processActionExit(mapping, form, request, response, errors);
                saveToken(request);
            } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_SCROLL_LEFT)) {
                setHandled(request);
                actionForward = processActionScrollLeft(mapping, formIn, request, response, errors);
                saveToken(request);
            } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_SCROLL_RIGHT)) {
                setHandled(request);
                actionForward = processActionScrollRight(mapping, formIn, request, response, errors);
                saveToken(request);
            } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_SCROLL_TO_FIRST_PAGE)) {
                setHandled(request);
                actionForward = processActionScrollToFirstPage(mapping, formIn, request, response, errors);
                saveToken(request);
            } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_SCROLL_TO_LAST_PAGE)) {
                setHandled(request);
                actionForward = processActionScrollToLastPage(mapping, formIn, request, response, errors);
                saveToken(request);
            } else if (!isHandled(request) && action.equalsIgnoreCase(ACTION_SCROLL_TO)) {
                setHandled(request);
                actionForward = processActionScrollTo(mapping, formIn, request, response, errors);
                saveToken(request);
            } else if (!isHandled(request) && action.length() > 0) {
                Logger.all(this, "otherExecute(), action=" + action);
                actionForward = handlePageEvent(mapping, form, request, response, errors);
                setHandled(request);
            }
            saveErrors(request, errors);
        } catch (Exception e) {
            Logger.logExceptions(this, e);
        }
        
        return actionForward;
	}

	
	 protected ActionForward processStatus(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
	            HttpServletResponse response, ActionErrors errors, String rb_status) {
		 return processOtherStatus(mapping, formIn, request, response, errors, rb_status);
	 }
	 
	protected void initAction(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response,
            ActionErrors errors) {
      
    }
	
	protected void initForm(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response,
            ActionErrors errors) {
		ActionForward actionForward = null;
        try {
            actionForward = new ActionForward(mapping.getInput());
            SimpleUserStyleForm form = (SimpleUserStyleForm) formIn;
            HttpSession session = request.getSession(false);
            form = (SimpleUserStyleForm) this.createUserForm(mapping, form, request, response, errors);
            this.AfterInitForm(mapping, form, request, response, errors);
            session.setAttribute(getUserFormSessionName(), form);
        } catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
            Logger.logExceptions(this, e);
        }
    }
	
	protected void AfterInitForm(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response,
            ActionErrors errors) {
		
	}
	
	 protected SimpleUserStyleForm createUserForm(ActionMapping mapping, SimpleUserStyleForm originalForm, HttpServletRequest request,
	            HttpServletResponse response, ActionErrors errors) throws Exception {
            HttpSession session = request.getSession(false);
            User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);
		    SimpleUserStyleForm result = (SimpleUserStyleForm) getUserFormClass().newInstance();
	        result.setErrMsgMap(originalForm.getErrMsgMap());
	        result.setSysLangCode((String) request.getSession(false).getAttribute(SESSION_SYSTEM_LANG));
	        result.setMenuObjectList(originalForm.getMenuObjectList());        
	        result.setIsReadOnly(originalForm.getIsReadOnly());
	        result.setRoCaller(originalForm.getRoCaller());
	        result.setFormType(originalForm.getFormType());
	        this.afterCreateUserForm(mapping, originalForm, result, request, response, errors);
	        return result;
	}
	 
	protected void afterCreateUserForm(ActionMapping mapping, SimpleUserStyleForm originalForm, SimpleUserStyleForm newMasterForm, HttpServletRequest request,
	            HttpServletResponse response, ActionErrors errors) throws Exception {
	}
	
	protected String getSessionSimpleUserStatus() {
        return SimpleConstants.SESSION_SIMPLE_USER_STATUS;
    }
	
	 protected ActionForward processActionExit(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
	            HttpServletResponse response, ActionErrors errors) {

	        ActionForward actionForward = null;
	        try {	        	
	            SimpleUserStyleForm form = (SimpleUserStyleForm) formIn;
	            HttpSession session = request.getSession(false);

	            actionForward = new ActionForward(mapping.getInput());

	            session.removeAttribute(getUserFormSessionName());
	            actionForward = mapping.findForward("default");
//
//	            if (getKeepSearchResult()) {
//	                session.setAttribute(getSessionReset(), GENERIC_YES);
//	            }

	            if (getNeedSetGotoURL()) {
	                form.setGotoURL(actionForward.getPath());
	            }
	            //cleanup(mapping, formIn, request, response, errors);
	        } catch (Exception e) {
	            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.error", e.getMessage()));
	            Logger.logExceptions(this, e);
	        }
	        return actionForward;
	    }
    
}
